import 'dart:async';
import 'dart:isolate';

import 'package:flutter_track/base/base_logger.dart';
import 'package:flutter_track/base/base_tracker.dart';
import 'package:flutter_track/tracker_isolate/tracker_isolate.dart';
import 'package:flutter_track/base/tracker_message_bean.dart';

/// Track的管理者
class FlutterTrackManager {
  final BaseIsolateTracker _trackerIsolate = TrackerIsolate();

  /// 初始化任务
  void init() {
    /// 需要确保
    /// 初始化任务，由 tracker isolate 发送到 main isolate 的
    _trackerIsolate.initTracker(
      handleMainMessage: ({required message, trackerSendPort}) async {
        switch (message.action) {
          case SendAction.microTaskDone:
            Log.info(
              tag: tag,
              message: "listen microtask done. $message",
            );
            break;
          case SendAction.exit:

            /// 收到 tracker isolate 的退出指令
            /// 是否需要在 mainisolate 做一些释放工作 ?
            Log.info(tag: tag, message: message.toString());
            break;
          case SendAction.sendDone:
            Log.info(
              tag: tag,
              message: "listen done. $message",
            );

            break;
          case SendAction.sendMicroTask:

            /// 创建一个刚刚接收到的microtask任务的副本，并且把副本的状态变更（默认任务完成）
            var microTaskDonemessage = message.copy();
            microTaskDonemessage.action = SendAction.microTaskDone;
            microTaskDonemessage.msg = "main isolate microtask done";
            microTaskDonemessage.exception = null;

            _scheduleMicroTaskAndSend(
              microTask: () {
                Log.info(
                  tag: tag,
                  message: "main isolate do micro task",
                );
              },
              sendPort: trackerSendPort,
              microTaskDoneSend: microTaskDonemessage,
            );
            break;
          case SendAction.trackTask:
            Log.info(tag: tag, message: "do track log info....2");
            break;
          default:
            break;
        }
      },
    );
  }

  /// 微型任务发送到主队列中
  void _scheduleMicroTaskAndSend({
    void Function()? microTask,
    SendPort? sendPort,
    required ActionMessage microTaskDoneSend,
  }) {
    if (microTask == null) {
      return;
    }
    if (sendPort == null) {
      return;
    }
    scheduleMicrotask(() async {
      var hasCrash = false;
      try {
        microTask();
      } on Exception catch (e) {
        microTaskDoneSend.exception = e;
        hasCrash = true;
      }

      sendPort.send(microTaskDoneSend);

      Log.info(
        tag: tag,
        message:
            "micro task done.. debug name: ${Isolate.current.debugName}, crash? $hasCrash",
      );
      if (hasCrash) {
        Log.info(
          tag: tag,
          message: "crash message: ${microTaskDoneSend.exception?.toString()}",
        );
      }
    });
  }

  /// 开始执行tracker的流程
  void doTrack(int? baseIsolateInstructions, int? baseVm) {
    _trackerIsolate.doTrack(baseIsolateInstructions, baseVm);
  }

  void closeTrack() {
    _trackerIsolate.closeTracker();
  }

  String getPrintStr() {
    return "print something... in FlutterTrackManager...";
  }
}
